package eastmoney

import (
	"strings"

	"gitee.com/lenchu/stock-api-go/api"
)

// JYS			CodeType	MarketType	MktNum	SecurityType
// HK				HK				5						116			19
// 2				SH				1						1				1
// 6				SZ				2						0				2
// OTCFUND	JJ				6						150			17
// QQZS			HKI				5						100			11
// 1				CSI				1						1				5
type eastMoneyCode struct {
	marketNum string
	code      string
}

var marketNumStandardCodeTypeMap = map[string]string{
	"1":   api.STOCK_TYPE_SH,
	"0":   api.STOCK_TYPE_SZ,
	"116": api.STOCK_TYPE_HK,
	"150": api.STOCK_TYPE_JJ,
	"100": api.STOCK_TYPE_HKI,
	// "7": "US",
}
var standardCodeTypeMarketNumMap = make(map[string]string)

func init() {
	for k, v := range marketNumStandardCodeTypeMap {
		standardCodeTypeMarketNumMap[v] = k
	}
}

func (this *eastMoneyCode) getStandardCode() string {
	standardCodeType := marketNumStandardCodeTypeMap[this.marketNum]
	if strings.HasPrefix(this.code, CHI_PREFIX_SH) && standardCodeType == api.STOCK_TYPE_SH {
		standardCodeType = api.STOCK_TYPE_CSI
	}
	if strings.HasPrefix(this.code, CHI_PREFIX_SZ) && standardCodeType == api.STOCK_TYPE_SZ {
		standardCodeType = api.STOCK_TYPE_CSI
	}
	return this.code + api.CODE_SUFFIX_SEPARATOR + standardCodeType
}
func (this *eastMoneyCode) getEmCode() string {
	return this.marketNum + MARKET_NUM_CODE_SEPARATOR + this.code
}

func resolveCSI(code string, suffix string) *eastMoneyCode {
	if suffix == api.STOCK_TYPE_CSI {
		if strings.HasPrefix(code, CHI_PREFIX_SH) {
			emCode := eastMoneyCode{
				code:      code,
				marketNum: standardCodeTypeMarketNumMap[api.STOCK_TYPE_SH],
			}
			return &emCode
		} else if strings.HasPrefix(code, CHI_PREFIX_SZ) {
			emCode := eastMoneyCode{
				code:      code,
				marketNum: standardCodeTypeMarketNumMap[api.STOCK_TYPE_SZ],
			}
			return &emCode
		} else {
			return nil
		}
	} else {
		return nil
	}
}
func fromStandardCodeToEastmoneyCode(standardCode string) *eastMoneyCode {
	before, after, found := strings.Cut(standardCode, api.CODE_SUFFIX_SEPARATOR)
	emCode := eastMoneyCode{}
	if !found {
		return nil
	}
	emCode.code = before
	marketNum, exists := standardCodeTypeMarketNumMap[after]
	if !exists {
		return resolveCSI(before, after)
	}
	emCode.marketNum = marketNum
	return &emCode
}

func fromCodeAndMarketNumToEastmoneyCode(code string, marketNum string) *eastMoneyCode {
	_, exists := marketNumStandardCodeTypeMap[marketNum]
	if !exists {
		return nil
	}
	emCode := eastMoneyCode{
		code:      code,
		marketNum: marketNum,
	}
	return &emCode
}
